package mongoex

import (
	"context"
	"github.com/sirupsen/logrus"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/readpref"
	"sync"
	"time"
)

const (
	maxPoolSize = 100
	minPoolSize = 10
	maxIdleTime = 10 * time.Second
)

var once sync.Once
var mongoClient *mongo.Client

type Config struct {
	Url        string `mapstructure:"url" json:"url" yaml:"url" `
	Username   string `mapstructure:"username" json:"username" yaml:"username"`
	Password   string `mapstructure:"password" json:"password" yaml:"password"`
	AuthSource string `mapstructure:"authSource" json:"authSource" yaml:"authSource"`
}

func InitMongoClient(config Config) *mongo.Client {
	once.Do(func() {
		opts := options.Client()
		opts.ApplyURI(config.Url)
		opts.SetMaxPoolSize(maxPoolSize).SetMinPoolSize(minPoolSize).SetMaxConnIdleTime(maxIdleTime)
		opts.SetAuth(options.Credential{
			AuthSource: config.AuthSource,
			Username:   config.Username,
			Password:   config.Password,
		})
		client, err := mongo.Connect(opts)
		if err != nil {
			logrus.Panic("mongo connect fail")
		}
		if err = client.Ping(context.Background(), readpref.Primary()); err != nil {
			logrus.Panic("mongo ping fail")
		}
		mongoClient = client
	})
	return mongoClient
}

func GetClient() *mongo.Client {
	return mongoClient
}
